<template>
  <div class="h-[850px] bg-gray-50 pt-10">
    <div class="max-w-screen-xl mx-auto px-11 flex">
      <!-- Left Menu -->
      <div class="w-52 space-y-5">
        <div class="p-3 bg-white rounded-xl shadow-sm">
          <div
            v-for="item in menuList"
            :key="item.value"
            class="px-5 py-2 hover:bg-gray-50 transition-colors duration-200 leading-9 rounded-xl h-13 cursor-pointer"
            :class="item.value === actionMenu ? 'bg-gray-50 font-medium' : ''"
            @click="actionMenu = item.value"
          >
            {{ item.label }}
          </div>
        </div>
      </div>

      <!-- Main Content -->
      <div class="flex-1 ml-7 mb-10">
        <!-- Account Section -->
        <div v-if="actionMenu === 0" class="bg-white rounded-xl shadow-sm">
          <div class="max-w-5xl mx-auto px-8">
            <!-- Phone Number Section -->
            <div class="h-30 flex items-center justify-between text-base font-medium border-b border-gray-100">
              <div class="flex items-center space-x-5">
                <img src="@/assets/login/phone.svg" alt="phone" class="w-6 h-6" />
                <span>{{ AuthStore.maskedPhone }}</span>
              </div>
              <!-- <v-btn
                variant="tonal"
                rounded="pill"
                @click="handleChangePhone"
              >
                更换手机号
              </v-btn> -->
            </div>

            <!-- Password Login Section -->
            <div class="h-30 flex items-center justify-between text-base font-medium border-b border-gray-100">
              <div class="flex items-center space-x-5">
                <img src="@/assets/login/password.svg" alt="password" class="w-6 h-6" />
                <span>密码登录</span>
              </div>
              <v-btn
                variant="tonal"
                rounded="pill"
                @click="changeUser"
              >
                {{ AuthStore.userInfo?.is_up_login ? "关闭" : "开启" }}
              </v-btn>
            </div>

            <!-- Logout Section -->
            <div class="h-30 flex items-center justify-between text-base font-medium">
              <div class="flex items-center space-x-5">
                <img src="@/assets/login/password.svg" alt="logout" class="w-6 h-6" />
                <span>退出登录</span>
              </div>
              <v-btn
                variant="tonal"
                rounded="pill"
                color="error"
                @click="loginOut"
              >
                退出登录
              </v-btn>
            </div>
          </div>
        </div>

        <!-- Order Table Section -->
        <div v-else-if="actionMenu === 1" class="bg-white rounded-xl shadow-sm">
          <v-card flat class="pa-10" rounded="xl">
            <!-- Search and Filter Bar -->
            <div class="mb-6 flex items-center gap-4">
              <!-- <v-text-field
                v-model="search"
                prepend-inner-icon="mdi-magnify"
                label="搜索素材"
                single-line
                hide-details
                density="comfortable"
                class="max-w-xs"
                variant="outlined"
                rounded="lg"
                @update:model-value="handleSearch"
              ></v-text-field> -->

              <v-select
                v-model="selectedStatus"
                :items="statusOptions"
                label="订单状态"
                hide-details="auto"
                class="max-w-xs"
                clearable
                variant="outlined"
                rounded="lg"
                density="comfortable"
                @update:model-value="handleStatusChange"
              ></v-select>
            </div>

            <v-divider class="mb-6"></v-divider>

            <!-- Enhanced Data Table -->
            <v-data-table-server
              :headers="headers"
              :items="orderData"
              :loading="loading"
              :search="search"
              :items-per-page="fetchOrderFetch.limit"
              :page="currentPage"
              :items-length="totalItems"
              :items-per-page-options="itemsPerPageOptions"
              hover
              height="500"
              density="compact"
              class="elevation-1 rounded-lg"
              @update:page="handlePageChange"
              @update:items-per-page="handleItemsPerPageChange"
            >
              <template v-slot:loading>
                <v-skeleton-loader type="table-row@10"></v-skeleton-loader>
              </template>

              <!-- Image Column -->
              <template v-slot:item.image="{ item }">
                <v-card class="ma-2 flex items-center justify-center" elevation="0 " rounded="lg" >
                  <v-img
                    :src="getFullPath(item.cover_image)"
                    height="48"
                    width="48"
                    cover
                    class="rounded-lg"
                  ></v-img>
                </v-card>
              </template>

              <!-- Price Column -->
              <template v-slot:item.price="{ item }">
                <div class="font-medium text-primary">
                  {{ Number(item.price).toFixed(2)=="0.00"?'免费': '¥'+ Number(item.price).toFixed(2) }}
                </div>
              </template>

              <!-- Order Status Column -->
              <template v-slot:item.order_status="{ item }">
                <v-chip
                  :color="getStatusColor(item.order_status)"
                  size="small"
                  class="font-medium"
                  variant="flat"
                >
                  {{ getStatusText(item.order_status) }}
                </v-chip>
              </template>

              <!-- Create Time Column -->
              <template v-slot:item.create_time="{ item }">
                <div>
                  {{ formatDate(item.create_time) }}
                </div>
              </template>

              <!-- Actions Column -->
              <template v-slot:item.actions="{ item }">
                <v-btn
                  v-if="item.order_status === 3 && isDownloadable(item)"
                  color="primary"
                  size="small"
                  variant="flat"
                  rounded
                  @click="handleDownload(item)"
                >
                  下载素材
                </v-btn>
                <v-btn
                  v-else-if="item.order_status === 1 "
                  color="warning"
                  size="small"
                  variant="flat"
                  rounded
                  @click="handlePay(item)"
                >
                  去支付
                </v-btn>
              </template>
            </v-data-table-server>
          </v-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useAuthStore } from "@/stores/auth";
import { changeUserInfo } from "@/api/login";
import { getOrderList } from "@/api/order";
import dayjs from 'dayjs';
import { Number } from "core-js";
import { getFullPath } from "@/utils/tools";

const router = useRouter();
const AuthStore = useAuthStore();
const loading = ref(true);

// Menu state
const actionMenu = ref(0);
const menuList = [
  { label: "账号", value: 0 },
  { label: "购买记录", value: 1 },
];

// Table state
const search = ref("");
const selectedStatus = ref(null);
const statusOptions = [
  { title: '全部', value: null },
  { title: '待支付', value: 1 },
  { title: '取消支付', value: 2 },
  { title: '已支付', value: 3 },
  { title: '退款中', value: 4 },
  { title: '已退款', value: 5 },
];

const headers = [
  { title: "订单号", value: "order_number", width: "25%", align: "center", nowrap: true },
  { title: "素材名称", value: "name", width: "15%", align: "center", nowrap: true },
  { title: "预览", value: "image", width: "15%", align: "center", nowrap: true },
  { title: "价格", value: "price", width: "5%", align: "center", nowrap: true },
  { title: "订单状态", value: "order_status", width: "10%", align: "center", nowrap: true },
  { title: "创建时间", value: "created_time", width: "15%", align: "center", nowrap: true },
  { title: "操作", value: "actions", width: "15%", sortable: false, align: "center", nowrap: true },
];

// Pagination and data state
const currentPage = ref(1);
const itemsPerPageOptions = [
  { value: 5, title: '5条/页' },
  { value: 10, title: '10条/页' },
  { value: 20, title: '20条/页' },
];
const fetchOrderFetch = ref({
  offset: 1,
  limit: 10,
  order_status: null,
  keyword: "",
});
const totalItems = ref(0);
const orderData = ref([]);

// Helper functions
const getStatusText = (status) => {
  const statusMap = {
    1: '待支付',
    2: '取消支付',
    3: '已支付',
    4: '退款中',
    5: '已退款'
  };
  return statusMap[status] || '未知状态';
};

const getStatusColor = (status) => {
  const statusColors = {
    "1": 'warning',  // 待支付
    "2": 'grey',     // 取消支付
    "3": 'success',  // 已支付
    "4": 'info',     //
    "5": 'error'     //
  };
  return statusColors[status] || 'grey';
};

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

const isDownloadable = (item) => {
  return dayjs(item.download_timeout_time).valueOf() > Date.now();
};

// Event handlers
const handleChangePhone = () => {
  // Implement phone change logic
  console.log('Changing phone number');
};

const handleDownload = (item) => {
  // Implement download logic
  console.log('Downloading item:', item);
  //?img=/media/material_files/4_XlQ22Gx.png&id=8&categoryId=4&name=Houdini工程0&fileType=视频素材&price=0.01&lifespan=20
  const url = `/buy?id=${item.material_id}&categoryId=${item.first_category}&orderNumber=${item.order_number}`;
  router.push(url);
};

const handlePay = (item) => {
  // Implement payment logic
  const url = `/buy?id=${item.material_id}&categoryId=${item.first_category}&orderNumber=${item.order_number}`;
  router.push(url);};

const handleSearch = () => {
  fetchOrderFetch.value.keyword = search.value;
  currentPage.value = 1;
  fetchOrderList();
};

const handleStatusChange = () => {
  fetchOrderFetch.value.order_status = selectedStatus.value;
  currentPage.value = 1;
  fetchOrderList();
};

const changeUser = async () => {
  try {
    const res = await changeUserInfo({
      is_up_login: !AuthStore.userInfo.is_up_login,
    });
    AuthStore.fetchUserInfo(res.data);
  } catch (error) {
    console.error('Error changing user info:', error);
  }
};

const loginOut = () => {
  router.push("/");
  AuthStore.logout();
};

// API calls and data fetching
const fetchOrderList = async () => {
  try {
    loading.value = true;
    const { data, count } = await getOrderList({
      ...fetchOrderFetch.value,
      offset: (currentPage.value - 1) * fetchOrderFetch.value.limit,
    });
    orderData.value = data;
    totalItems.value = Number(count);
  } catch (error) {
    console.error('Error fetching order list:', error);
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (page) => {
  currentPage.value = page;
  fetchOrderFetch.value.offset = page;
  fetchOrderList();
};

const handleItemsPerPageChange = (itemsPerPage) => {
  fetchOrderFetch.value.limit = itemsPerPage;
  currentPage.value = 1;
  fetchOrderList();
};

// Lifecycle hooks
onMounted(() => {
  fetchOrderList();
});
</script>

<style scoped>
.h-30 {
  height: 120px;
}
</style>
